/*
 * Wazuh Vulnerability Scanner - Unit Tests
 * Copyright (C) 2015, Wazuh Inc.
 * September 21, 2023.
 *
 * This program is free software; you can redistribute it
 * and/or modify it under the terms of the GNU General Public
 * License (version 2) as published by the FSF - Free Software
 * Foundation.
 */

#include "eventDeleteInventory_test.hpp"
#include "../../../../shared_modules/utils/flatbuffers/include/rsync_generated.h"
#include "../../../../shared_modules/utils/flatbuffers/include/rsync_schema.h"
#include "../../../../shared_modules/utils/flatbuffers/include/syscollector_deltas_generated.h"
#include "../../../../shared_modules/utils/flatbuffers/include/syscollector_deltas_schema.h"
#include "../scanOrchestrator/eventDeleteInventory.hpp"
#include "MockOsDataCache.hpp"
#include "TrampolineOsDataCache.hpp"
#include "TrampolineRemediationDataCache.hpp"
#include "flatbuffers/flatbuffer_builder.h"
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "json.hpp"

using ::testing::_;

namespace NSEventDeleteInventoryTest
{
    constexpr auto TEST_INVENTORY_DATABASE_PATH {"queue/vd/inventory"};

    const std::string DELTA_PACKAGES_DELETED_MSG =
        R"(
            {
                "agent_info": {
                    "agent_id": "001",
                    "agent_ip": "192.168.33.20",
                    "agent_name": "focal"
                },
                "data_type": "dbsync_packages",
                "data": {
                    "architecture": "amd64",
                    "checksum": "1e6ce14f97f57d1bbd46ff8e5d3e133171a1bbce",
                    "description": "library for GIF images library",
                    "format": "deb",
                    "groups": "libs",
                    "item_id": "ec465b7eb5fa011a336e95614072e4c7f1a65a53",
                    "multiarch": "same",
                    "name": "libgif7",
                    "priority": "optional",
                    "scan_time": "2023/08/04 19:56:11",
                    "size": 72,
                    "source": "giflib",
                    "vendor": "Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com>",
                    "version": "5.1.9-1",
                    "install_time": "1577890801"
                },
                "operation": "DELETED"
            }
        )";

    const std::string CVEID1 {"CVE-2024-5678"};
    const std::string CVEID2 {"CVE-2023-5362"};
} // namespace NSEventDeleteInventoryTest

using namespace NSEventDeleteInventoryTest;

void EventDeleteInventoryTest::SetUp()
{
    m_inventoryDatabase = std::make_unique<Utils::RocksDBWrapper>(TEST_INVENTORY_DATABASE_PATH);
    for (const auto& element : AFFECTED_COMPONENT_COLUMNS)
    {
        if (!m_inventoryDatabase->columnExists(element.second))
        {
            m_inventoryDatabase->createColumn(element.second);
        }
    }

    if (!m_inventoryDatabase->columnExists(OS_INITIAL_SCAN))
    {
        m_inventoryDatabase->createColumn(OS_INITIAL_SCAN);
    }
}

void EventDeleteInventoryTest::TearDown()
{
    spOsDataCacheMock.reset();
    spRemediationDataCacheMock.reset();
    m_inventoryDatabase->deleteAll();
    m_inventoryDatabase.reset();
    std::filesystem::remove_all(TEST_INVENTORY_DATABASE_PATH);
}

/*
 * @brief Test instantiation of the eventDeleteInventory class.
 */
TEST_F(EventDeleteInventoryTest, TestInstantiationOfTheEventInsertInventoryClass)
{
    // Instantiation of the eventDeleteInventory class.
    using scanContext_t = TScanContext<TrampolineOsDataCache, GlobalData, TrampolineRemediationDataCache>;
    EXPECT_NO_THROW(std::make_shared<TEventDeleteInventory<scanContext_t>>(*m_inventoryDatabase));
}

/*
 * @brief Test handleRequest of the eventDeleteInventory class (Package Delete).
 */
TEST_F(EventDeleteInventoryTest, TestHandleRequestPackageDelete)
{
    // Instantiation of the eventDeleteInventory class.
    m_inventoryDatabase->put("001_ec465b7eb5fa011a336e95614072e4c7f1a65a53", CVEID1, PACKAGE);

    auto eventDeleteInventory = std::make_shared<
        TEventDeleteInventory<TScanContext<TrampolineOsDataCache, GlobalData, TrampolineRemediationDataCache>>>(
        *m_inventoryDatabase);

    Os osData {.hostName = "osdata_hostname",
               .architecture = "osdata_architecture",
               .name = "osdata_name",
               .codeName = "osdata_codeName",
               .majorVersion = "osdata_majorVersion",
               .minorVersion = "osdata_minorVersion",
               .patch = "osdata_patch",
               .build = "osdata_build",
               .platform = "osdata_platform",
               .version = "osdata_version",
               .release = "osdata_release",
               .displayVersion = "osdata_displayVersion",
               .sysName = "osdata_sysName",
               .kernelVersion = "osdata_kernelVersion",
               .kernelRelease = "osdata_kernelRelease"};

    spOsDataCacheMock = std::make_shared<MockOsDataCache>();
    EXPECT_CALL(*spOsDataCacheMock, getOsData(_, _))
        .WillOnce(testing::Invoke(
            [&osData](const std::string&, Os& osDataResult)
            {
                osDataResult = osData;
                return true;
            }));

    spRemediationDataCacheMock = std::make_shared<MockRemediationDataCache>();
    EXPECT_CALL(*spRemediationDataCacheMock, getRemediationData(_)).WillRepeatedly(testing::Return(Remediation {}));

    // Mock scanContext.
    flatbuffers::Parser parser;
    ASSERT_TRUE(parser.Parse(syscollector_deltas_SCHEMA));
    ASSERT_TRUE(parser.Parse(DELTA_PACKAGES_DELETED_MSG.c_str()));
    uint8_t* buffer = parser.builder_.GetBufferPointer();
    std::variant<const SyscollectorDeltas::Delta*, const Synchronization::SyncMsg*, const nlohmann::json*>
        syscollectorDelta = SyscollectorDeltas::GetDelta(reinterpret_cast<const char*>(buffer));

    // Create a ScanContext object.
    auto scanContext =
        std::make_shared<TScanContext<TrampolineOsDataCache, GlobalData, TrampolineRemediationDataCache>>(
            syscollectorDelta);

    // Call handleRequest method.
    EXPECT_NO_THROW(eventDeleteInventory->handleRequest(scanContext));

    EXPECT_EQ(scanContext->m_elements.size(), 1);

    std::string expectedKey = "001_ec465b7eb5fa011a336e95614072e4c7f1a65a53_" + CVEID1;
    std::unordered_map<std::string, nlohmann::json>::const_iterator itElement;
    EXPECT_NE(itElement = scanContext->m_elements.find(CVEID1), scanContext->m_elements.end());

    std::string expectedValue =
        R"({"id":"001_ec465b7eb5fa011a336e95614072e4c7f1a65a53_)" + CVEID1 + R"(","operation":"DELETED"})";
    EXPECT_STREQ(itElement->second.dump().c_str(), expectedValue.c_str());

    std::string inventoryEntry;
    EXPECT_FALSE(m_inventoryDatabase->get("001_ec465b7eb5fa011a336e95614072e4c7f1a65a53", inventoryEntry, PACKAGE));
}
